#include "LoadShaders.h"
#include <iostream>

GLuint createProgram(std::string vertexShader, std::string fragmentShader){
	std::vector<GLuint> shaders;
	ShaderInfo vert = {GL_VERTEX_SHADER, vertexShader};
	GLuint v = loadShader(vert);
	shaders.push_back(v);
	ShaderInfo frag = {GL_FRAGMENT_SHADER, fragmentShader};
	GLuint f = loadShader(frag);
	shaders.push_back(f);
	return linkProgram(shaders);
}

GLuint linkProgram(std::vector<GLuint> shaderList){
	GLuint program = glCreateProgram();
	for(std::vector<GLuint>::iterator it = shaderList.begin(); it != shaderList.end(); ++it){
		glAttachShader(program, *it);
	}
	glLinkProgram(program);
	return program;
}

GLuint loadShader(ShaderInfo s){
	GLuint shader = glCreateShader(s.type);
	s.shader = shader;

	const GLchar* source = readShader((s.filename));
	glShaderSource(shader, 1, &source, NULL);
	glCompileShader(shader);

	GLint compiled;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
	if(!compiled){
		GLsizei len;
		glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);

		GLchar* log = new GLchar[len+1];
		glGetShaderInfoLog(shader, len, &len, log);
		std::cerr << "Shader compilation failed: " << log << std::endl;
		delete [] log;
	}
	return shader;
}

GLchar* readShader(std::string filename){
	FILE* infile;
	const char * c = filename.c_str();
	fopen_s(&infile, c, "rb");

    fseek(infile, 0, SEEK_END);
    int len = ftell(infile);
    fseek(infile, 0, SEEK_SET);	

    GLchar* source = new GLchar[len+1];
    fread(source, 1, len, infile);
    fclose(infile);
    source[len] = 0;

	return (GLchar*)source;
}
